package org.patterns.behavior.command.calculator;

import java.util.ArrayDeque;
import java.util.Deque;

//具体命令类
public class AddCommand extends AbstractCommand {
    private Adder adder;
    private final Deque<Integer> undoStack = new ArrayDeque<Integer>();
    private final Deque<Integer> redoStack = new ArrayDeque<Integer>();

    public AddCommand() {
        this.adder = new Adder();
    }

    //实现抽象命令类中声明的execute()方法，调用加法类的加法操作
    public int execute(int value) {
        this.undoStack.push(value);
        return adder.add(value);
    }

    //实现抽象命令类中声明的undo()方法，通过加一个相反数来实现加法的逆向操作
    @Override
    public int undo() {
        if (this.undoStack.isEmpty()) {
            throw new IllegalStateException("无法撤销：没有之前的操作。");
        }
        int value = this.undoStack.pop();
        this.redoStack.push(value);
        return adder.add(-value);
    }

    @Override
    public int redo() {
        if (this.redoStack.isEmpty()) {
            throw new IllegalStateException("无法恢复：没有之前的操作。");
        }
        int value = this.redoStack.pop();
        this.undoStack.push(value);
        return adder.add(value);
    }

    @Override
    public void save() {
        undoStack.clear();
        redoStack.clear();
    }
}
